﻿using System.Drawing;
using System.Drawing.Printing;
using System.IO;

namespace BatchPrint.Services;

public class PrinterManager
{
    private event Action<string>? PrintFinish;
    private event Action<Exception>? PrintError;
    private readonly PrintDocument _printDoc;

    public PrinterManager()
    {
        _printDoc = new PrintDocument();
    }

    /// <summary>
    /// 获取所有可用打印机
    /// </summary>
    /// <returns></returns>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822:将成员标记为 static", Justification = "<挂起>")]
    public string[] GetAvailablePrinters()
    {
        return PrinterSettings.InstalledPrinters.Cast<string>().ToArray();
    }

    /// <summary>
    /// 获取默认打印机
    /// </summary>
    /// <returns></returns>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822:将成员标记为 static", Justification = "<挂起>")]
    public string GetDefaultPrinter()
    {
        PrinterSettings settings = new PrinterSettings();
        return settings.PrinterName;
    }

    /// <summary>
    /// 打印文件
    /// </summary>
    /// <param name="filePath">文件路径</param>
    /// <param name="printerName">打印机名称</param>
    /// <exception cref="FileNotFoundException"></exception>
    /// <exception cref="InvalidOperationException"></exception>
    public void PrintFile(DImage img, string? printerName = null)
    {
        if (!string.IsNullOrEmpty(printerName))
        {
            _printDoc.PrinterSettings.PrinterName = printerName;
        }

        if (!_printDoc.PrinterSettings.IsValid)
        {
            throw new InvalidOperationException("指定的打印机无效");
        }

        _printDoc.PrintPage += (sender, printPage) =>
        {
            try
            {
                System.Drawing.Rectangle m = printPage.MarginBounds;

                if (img.Width / (double)img.Height > m.Width / (double)m.Height)
                {
                    m.Height = (int)(img.Height / (double)img.Width * m.Width);
                }
                else
                {
                    m.Width = (int)(img.Width / (double)img.Height * m.Height);
                }

                printPage!.Graphics!.DrawImage(img, m);
            }
            catch (Exception ex)
            {
                PrintError?.Invoke(ex);
                Console.WriteLine($"打印过程中发生错误: {ex.Message}");
            }
        };

        try
        {
            _printDoc.Print();
            PrintFinish?.Invoke("文件已成功发送到打印机");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"打印失败: {ex.Message}");
            PrintError?.Invoke(ex);
        }
    }

    //private void PrintImage(PrintPageEventArgs printPage, Image img)
    //{
    //    return;
    //    System.Drawing.Rectangle m = printPage.MarginBounds;

    //    if (img.Width / (double)img.Height > m.Width / (double)m.Height)
    //    {
    //        m.Height = (int)(img.Height / (double)img.Width * m.Width);
    //    }
    //    else
    //    {
    //        m.Width = (int)(img.Width / (double)img.Height * m.Height);
    //    }

    //    printPage!.Graphics!.DrawImage(img, m);
    //}

    //private void PrintPdf(PrintPageEventArgs printPage, string filePath)
    //{
    //    if (printDoc == null) return;

    //    var pdfDoc = PdfDocument.Load(filePath);
    //    var pageIndex = printDoc.PrinterSettings.FromPage - 1;
    //    if (pageIndex < 0 || pageIndex >= pdfDoc.PageCount) return;

    //    using var pageImage = pdfDoc.Render(pageIndex, 300, 300, true);
    //    var image = new Bitmap(pageImage);
    //    PrintImage(printPage, image);
    //}

    //private void PrintExcel(PrintPageEventArgs printPage, string filePath)
    //{
    //    var images = new ExcelToImageConverter(filePath).ConvertToImages();
    //    PrintImage(printPage, images.First());
    //}

    //private void PrintWord(PrintPageEventArgs printPage, string filePath)
    //{

    //}
}
